import { SEO } from '@/utils/seo'
import { Helmet } from '@umijs/max'
import { useLocation, useModel } from '@umijs/max'
import React, { useEffect, useState } from 'react'
import styles from './index.less'

const Works = () => {
  const { works } = useModel('global')
  const [worksIndex, setWorksIndex] = useState<number>(-1)
  const location = useLocation()
  useEffect(() => {
    // 回到网页顶部
    window.scrollTo({ top: 0 })
    const searchParams = Number(new URLSearchParams(location.search).get('type') || -1)
    setWorksIndex(searchParams)
  }, [location])

  const handleClick = (evt: React.MouseEvent<HTMLUListElement>) => {
    // 使用事件委托获取最近的 li 元素
    const target = evt.target as Element
    const liElement = target.closest('li')
    if (liElement) {
      const source = liElement.dataset.source
      if (source) {
        // 在新标签页打开链接
        window.open(source, '_blank')
      }
    }
  }
  
  // 获取当前选中的分类名称
  const currentCategoryName = worksIndex >= 0 && works && works[worksIndex] 
    ? works[worksIndex].category 
    : '全部作品';
    
  // 获取当前筛选的作品数据
  const filteredWorks = works?.filter((item, key) => {
    return worksIndex === -1 || key === worksIndex
  }) || [];

  return (
    <>
      <SEO 
        title={`${currentCategoryName} - Zusheng Studio作品集`}
        description={`Zusheng Studio的${currentCategoryName}作品展示，包括创意设计、网站开发和多媒体制作等项目。`}
        keywords={`Zusheng,${currentCategoryName},作品集,设计,创意项目`}
        url={`https://zusheng.cc/works${worksIndex >= 0 ? `?type=${worksIndex}` : ''}`}
      />
      {/* 添加作品集的结构化数据 */}
      <Helmet>
        <script type="application/ld+json">
          {JSON.stringify({
            "@context": "https://schema.org",
            "@type": "CollectionPage",
            "name": `${currentCategoryName} - Zusheng Studio作品集`,
            "description": `Zusheng Studio的${currentCategoryName}作品展示，包括创意设计、网站开发和多媒体制作等项目。`,
            "url": `https://zusheng.cc/works${worksIndex >= 0 ? `?type=${worksIndex}` : ''}`,
            "mainEntity": {
              "@type": "ItemList",
              "itemListElement": filteredWorks.flatMap((category, catIndex) => 
                category.data.map((item: { src: any; describeTitle: any; describeContent: any }, itemIndex: number) => ({
                  "@type": "ListItem",
                  "position": catIndex * 100 + itemIndex + 1,
                  "url": item.src || `https://zusheng.cc/works?type=${worksIndex === -1 ? catIndex : worksIndex}`,
                  "name": item.describeTitle,
                  "description": item.describeContent
                }))
              )
            }
          })}
        </script>
      </Helmet>
      <div className={styles.pageWorks + ' page'}>
        {works?.length > 0 &&
          works
            .filter((item, key) => {
              return worksIndex === -1 || key === worksIndex
            })
            .map((item: any, key) => (
              <section className={styles.section} key={'works-' + key}>
                <h2 id={'works-h-' + key} className={styles.category}>
                  {item.category}
                </h2>
                <ul className={styles.list} onClick={handleClick}>
                  {item.data.map((i: any) => (
                    <li data-source={i.src} className={styles.item} key={'works-item-' + i._id}>
                      <img className={styles.poster} src={i.poster} alt={`${item.category} - ${i.describeTitle}`} />
                      <div className={styles.info}>
                        <h3 className={styles.title}>{i.describeTitle}</h3>
                        {/* 技术栈 */}
                        <ul className={styles.tech}>
                          {i?.tech?.length > 0 &&
                            i.tech.map((tech: any, techKey: number) => (
                              <li key={'works-tech-' + techKey}>{tech}</li>
                            ))}
                        </ul>
                        <p className={styles.desc}>{i.describeContent}</p>
                      </div>
                    </li>
                  ))}
                </ul>
              </section>
            ))}
      </div>
    </>
  )
}

export default Works
